package com.tf.integrated.controller;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.ccssoft.m8.common.web.BaseController;
import com.tf.integrated.config.Config;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpMethod;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;
import java.util.regex.Pattern;

/**
 * 查询以图搜图结果详情
 *
 * @author allen
 * @date: 2020年9月14日上午10:56:20
 */
@Api(value = "查询以图搜图结果详细信息", description = "SearchSimilarDetailController")
@RestController
public class SearchSimilarDetailController extends BaseController {
    @ApiOperation("查询预警详细信息")
    @GetMapping("/search/similar/detail")
    @CrossOrigin(origins = "*", maxAge = 86400)
    public JSONObject searchSimilarDetail(@RequestParam Map<String, String> data) throws IOException {
        if (data != null && data.size() > 0) {
            String stype = data.get("type");
            String host = data.get("host");
            if (isExist(stype) && isExist(host)) {
                int type = Integer.parseInt(stype);
                if (type >= 1 && type <= 5) {
                    HttpMethod method = HttpMethod.GET;
                    String[] api = new String[]{"/search/byid/vehicles?", "/search/byid/tricycles?", "/search/byid/pedestrians?", "/search/byid/bikes?", "/search/byid/faces?"};
                    String[] typeInfo = new String[]{"VehicleInfo","TricycleInfo","PedestriansInfo","BikesInfo","FacesInfo"};
                    String disUrl = api[type - 1] + Config.buildMap(data);
                    HttpHeaders headers = new HttpHeaders();
                    headers.set("X-Token", Config.getmCurtoken(host));
                    String analyseResults = Config.client(Config.getStarturlpre(host) + disUrl, method, null, headers);
                    LogController.add(disUrl, LogController.METHOD_GET, 1);
                    JSONObject jsonObject = JSONObject.parseObject(analyseResults);
                    JSONObject jsonData = jsonObject.getJSONObject("Data");
                    if(jsonData!=null){
                        JSONArray list = jsonData.getJSONArray(typeInfo[type-1]);
                        if(list!=null&&list.size()>0){
                            for(int i=0;i<list.size();i++){
                                JSONObject obj = list.getJSONObject(i);
                                String fullPicPath = obj.getString("FullPicPath");
                                String objPicPath = obj.getString("ObjPicPath");
                                obj.put("FullPicPath",savePic(host,fullPicPath));
                                obj.put("ObjPicPath",savePic(host,objPicPath));
                            }
                        }
                    }
                    return jsonObject;
                }
            }
        }
        LogController.add("/search/similar/detail", LogController.METHOD_GET, 0);
        return new JSONObject();
    }

    public boolean isExist(String value) {
        return value != null && !value.equals("");
    }

    public boolean isInteger(String str) {
        Pattern pattern = Pattern.compile("^[-+]?[\\d]*$");
        return pattern.matcher(str).matches();
    }

    private String savePic(String host,String path) throws IOException {
        URL url = new URL(Config.getStarturlpre(host) +"/picture/?path="+path);
        URLConnection con = url.openConnection();
        con.setConnectTimeout(15*1000);
        con.setReadTimeout(15*1000);
        con.addRequestProperty("X-Token",Config.getmCurtoken(host));
        InputStream is = con.getInputStream();
        byte[] bs = new byte[256*1024];
        int len;
        String fileName = "SIMILAR"+System.currentTimeMillis()+".jpg";
        String filePath = Config.getMimgpath()+fileName;
        OutputStream os = new FileOutputStream(filePath);
        while ((len = is.read(bs)) != -1) {
            os.write(bs, 0, len);
        }
        os.close();
        is.close();
        return Config.getMurlpath()+fileName;
    }
}